<?php
/*
 * @Date: 2020-05-03 22:03:52
 * @名称: 上传控制器
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑人: 初雪桜
 * @LastEditTime: 2021-03-11 21:01:41
 * @FilePath: /Site/app/useradmin/controller/App.php
 */

namespace app\useradmin\controller;

use app\BaseController;
use app\useradmin\controller\DataBaseController\AppInfo;
use Ramsey\Uuid\Nonstandard\Uuid;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;

class App extends BaseController
{
    public function AppSetting()
    {
        return View::fetch("app/AppSetting", [
            "useradmin" => config("useradminConfig.useradmin_serverHost"),
        ]);
    }
    public function AppList()
    {

        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        if (!$user_info["is_web_admin"]) { //判断是否有权限访问此网页
            return View::fetch("OtherPage/Error", [
                "errorCode" => "AppSetting-Error-10000",
                "errorTitle" => "发生意外错误",
                "errorMsg" => "您没有权限访问",
            ]);
        }
        $essentialInformation = [
            "page" => input("page", 1), //第几页
            "onePageData" => input("onePageData", 15), //一页显示几个
            "uorce_update" => input("uorce_update", 999999999999999),
            "disable" => input("disable", 999999999999999),
        ];
        $selectWhere = []; //设置查询条件
        switch ($essentialInformation["uorce_update"]) { //因为case是 == 不判断类型 所以如果是 null那就是和0一样了 所以用“nnull”
            case 0: //不是强制更新
                $selectWhere["app_info.uorce_update"] = 0;
                break;
            case 1: //是强制更新
                $selectWhere["app_info.uorce_update"] = 1;
                break;
        }
        switch ($essentialInformation['disable']) {
            case 0: //不是强制更新
                $selectWhere["app_info.disable"] = 0;
                break;
            case 1: //是强制更新
                $selectWhere["app_info.disable"] = 1;
                break;
        }

        $AppInfo = new AppInfo($this->app);
        $AppAllInfo = $AppInfo->Select($essentialInformation['page'], $essentialInformation['onePageData'], $selectWhere)["data"];
        $appList = $AppAllInfo["AppList"];
        $Request = new Request();
        $isAjax = $Request::isAjax(); //判断是不是ajax
        if ($isAjax) {
            return json_decode(successJsonReturn([
                "appList" => $appList,
                "appListCount" => $AppAllInfo["Count"],
                "essentialInformation" => $essentialInformation,
            ])->getContent(), true);
        } else {
            return View::fetch("app/AppList/AppList", [
                "useradmin" => config("useradminConfig.useradmin_serverHost"),
                "appList" => $appList,
                "appListCount" => $AppAllInfo["Count"],
                "essentialInformation" => $essentialInformation,
            ]);
        }
    }
    public function SetIsUorceUpdate()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        if (!$user_info["is_web_admin"]) { //判断是否有权限访问此网页
            return View::fetch("OtherPage/Error", [
                "errorCode" => "AppSetting-Error-10000",
                "errorTitle" => "发生意外错误",
                "errorMsg" => "您没有权限访问",
            ]);
        }
        $app_id = input("app_id");
        $version = input("version");
        $uuid_id = input("uuid_id");
        if ($app_id == null || $version == null || $uuid_id == null) {
            return json_decode(errorJsonReturn("Admin-AppSetting-IsUorceUpdate-10000")->getContent(), true);
        }
        $appInfo = Db::table("app_info")
            ->where([
                "id" => $app_id,
                "_id" => $uuid_id,
                "version" => $version,
            ])
            ->order("id desc")
            ->find();
        if (!$appInfo) { //判断查询到了应用信息了吗
            return json_decode(errorJsonReturn("Admin-AppSetting-IsUorceUpdate-10001")->getContent(), true);
        } else {
            // 查询到了
            $uorce_update = $appInfo['uorce_update'];
            if ($uorce_update) { //判断是否强制更新 1是强制更新 0不强制更新
                $uorce_update = 0;
            } else {
                $uorce_update = 1;
            }
        }
        $updateState = Db::table("app_info")
            ->where($appInfo)
            ->update([
                "uorce_update" => $uorce_update,
            ]);
        if ($updateState) {
            return json_decode(successJsonReturn(["uorce_update" => $uorce_update, "updateState" => $updateState])->getContent(), true);
        } else {
            return json_decode(errorJsonReturn("Admin-AppSetting-IsUorceUpdate-10002")->getContent(), true);
        }
    }
    public function SetIsDisable()
    {
        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        if (!$user_info["is_web_admin"]) { //判断是否有权限访问此网页
            return View::fetch("OtherPage/Error", [
                "errorCode" => "AppSetting-Error-10000",
                "errorTitle" => "发生意外错误",
                "errorMsg" => "您没有权限访问",
            ]);
        }
        $app_id = input("app_id");
        $version = input("version");
        $uuid_id = input("uuid_id");
        if ($app_id == null || $version == null || $uuid_id == null) {
            return json_decode(errorJsonReturn("Admin-AppSetting-SetIsDisable-10000")->getContent(), true);
        }
        $appInfo = Db::table("app_info")
            ->where([
                "id" => $app_id,
                "_id" => $uuid_id,
                "version" => $version,
            ])
            ->order("id desc")
            ->find();
        if (!$appInfo) { //判断查询到了应用信息了吗
            return json_decode(errorJsonReturn("Admin-AppSetting-SetIsDisable-10001")->getContent(), true);
        } else {
            // 查询到了
            $disable = $appInfo['disable'];
            if ($disable) { //判断是否强制更新 1是强制更新 0不强制更新
                $disable = 0;
            } else {
                $disable = 1;
            }
        }
        $updateState = Db::table("app_info")
            ->where($appInfo)
            ->update([
                "disable" => $disable,
            ]);
        if ($updateState) {
            return json_decode(successJsonReturn(["disable" => $disable, "updateState" => $updateState])->getContent(), true);
        } else {
            return json_decode(errorJsonReturn("Admin-AppSetting-SetIsDisable-10002")->getContent(), true);
        }
    }
    public function AddAppInfo()
    {
        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        if (!$user_info["is_web_admin"]) { //判断是否有权限访问此网页
            return View::fetch("OtherPage/Error", [
                "errorCode" => "AppSetting-Error-10000",
                "errorTitle" => "发生意外错误",
                "errorMsg" => "您没有权限访问",
            ]);
        }

        return View::fetch("app/AppList/AddAppInfo", [
            "useradmin" => config("useradminConfig.useradmin_serverHost"),
        ]);
    }
    public function AddAppinfoToDataBase()
    {
        $token = cookie("Authorization");
        $userTokenVerificationParse = ParseUserToken($token, true, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        if (!$user_info["is_web_admin"]) { //判断是否有权限访问此网页
            return View::fetch("OtherPage/Error", [
                "errorCode" => "AppSetting-Error-10000",
                "errorTitle" => "发生意外错误",
                "errorMsg" => "您没有权限访问",
            ]);
        }
        $platform = (int)input("post.platform"); //类型
        $key = input("post.key"); //密钥
        $private_key = input("post.private_key"); //私钥
        $version = input("post.version"); //版本
        $build_version = input("post.build_version"); //编译版本
        $update_info = input("post.update_info"); //编译版本
        $download_url = input("post.download_url"); //更新日志
        $is_app =  Db::table('app_info') // 判断有没有重复的 密钥公钥
            ->whereOr([
                "key" => "$key", //应用密钥
                "private_key" => "$private_key", //私钥
            ])
            ->find();
        if ($is_app) {
            return json_decode(errorJsonReturn("Admin-AppSetting-addApp-10001")->getContent(), true);
        }
        $apId = randIdStructure(999999999, false); //应用id
        $insertId = Db::table('app_info')
            ->insertGetId([
                "_id" => $apId, //应用id
                "update_info" => "$update_info", //更新日志
                "key" => "$key", //应用密钥
                "platform" => "$platform", //ios 安卓
                "version" => "$version", //应用版本
                "build_version" => "$build_version", //编译版本
                "private_key" => "$private_key", //私钥
                "uorce_update" => 0, //是否强制更新
                "minimum_version_number" => null, //强制更新最低版本号
                "download_url" => "$download_url", //下载地址
                "disable" => 0, //是否禁用
                "disable_info" => null, //禁用原因
                "update_user_id" => "$user_info[_id]", //上传人id
                "upload_time" => date("Y-m-d H:i:s"), //上传时间
            ]);
        $returnData = [
            "id" => $insertId,
            "_id" => $apId,
            "update_info" => $update_info,
            "platform" => $platform,
            "version" => $version,
            "build_version" => $build_version,
            "uorce_update" => 0,
            "minimum_version_number" => null,
            "download_url" => $download_url,
            "disable" => 0,
            "disable_info" => null,
            "update_user_id" => $user_info["_id"],
            "upload_time" => date("Y-m-d H:i:s"),
            "name" => $user_info["name"],
        ];
        return json_decode(successJsonReturn([
            'insertInfo' => $returnData
        ])->getContent(), true);
    }
    public function DeleteAppinfoToDataBase()
    {
        $token = cookie("Authorization");;
        $userTokenVerificationParse = ParseUserToken($token, true, true);
        if ($userTokenVerificationParse['code'] != 200) {
            return json($userTokenVerificationParse);
        }
        $user_info = $userTokenVerificationParse["data"]["user_info"];
        if (!$user_info["is_web_admin"]) { //判断是否有权限访问此网页
            return View::fetch("OtherPage/Error", [
                "errorCode" => "AppSetting-Error-10000",
                "errorTitle" => "发生意外错误",
                "errorMsg" => "您没有权限访问",
            ]);
        }
        $app_id = input("app_id");
        $version = input("version");
        $uuid_id = input("uuid_id");
        if ($app_id == null || $version == null || $uuid_id == null) {
            return json_decode(errorJsonReturn("Admin-AppSetting-IsUorceUpdate-10000")->getContent(), true);
        }
        $appList = Db::table('app_info')
            ->where([
                "_id" => $uuid_id,
                "version" => $version,
                "id" => $app_id,
            ])
            ->select();
        if (count($appList) != 1) {
            return json_decode(errorJsonReturn("Admin-AppSetting-deleteApp-10000")->getContent(), true);
        }
        $deleteState = Db::table('app_info')
            ->where($appList[0])
            ->delete();
        if ($deleteState) {
            return json_decode(successJsonReturn([])->getContent(), true);
        } else {
            return json_decode(errorJsonReturn("Admin-AppSetting-deleteApp-10001")->getContent(), true);
        }
    }
}
